package edu.usc.libtalk;

import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import edu.usc.libtalk.R.color;
import edu.usc.libtalk.task.GetJSONArrayTask;
import edu.usc.libtalk.utils.ApplicationService;
import edu.usc.libtalk.utils.Globals;
import edu.usc.libtalk.utils.InternalConstant;

public class MessageBoardActivity extends Activity implements InternalConstant {

	private static final String TAG = "MessageBoardActivity";	
	private TableLayout msgTable;
	private JSONArray messages;
	private EditText  message_et;
	private Button message_bn;
	private String library;
	private String selected_level;
	private String selected_seat;
	private String deviceID;
	private String username;
	private Intent intent;
	private InputMethodManager imm;	
	private Globals globalObject;
	
	private Timer autoUpdate;
	private int msg_len = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
    	super.onCreate(savedInstanceState);
    	
        // Customize menu title 
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        
        setContentView(R.layout.activity_message_board);
        
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title_no_buttons);        
        
        // to save the chat data locally incase the user wants to
        // email
        globalObject = Globals.getInstance();
        
	    library = ApplicationService.getLibrary();
	    deviceID = ApplicationService.getDeviceID();
	    intent = getIntent();
	    selected_level = intent.getStringExtra(SELECTED_LEVEL);
	    selected_seat = intent.getStringExtra(SELECTED_SEAT);
	    username = ApplicationService.getUserName();
        
	    msgTable = (TableLayout) findViewById(R.id.message_table);
	    message_et = (EditText) findViewById(R.id.message_board_edittext);
	    message_bn = (Button) findViewById(R.id.message_board_button);	   
		imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
	    
	    message_et.addTextChangedListener(new TextWatcher() { 
	        public void  afterTextChanged (Editable s){
	        	if(s.length() == 0) {
	        		message_bn.setEnabled(false);
	        	} else {
	        		message_bn.setEnabled(true);
	        	}
	       } 
	       public void  beforeTextChanged  (CharSequence s, int start, int count, int after){ 

	       } 
	       public void  onTextChanged  (CharSequence s, int start, int before, int count) { 
	    	   
	       }
	    });
	    
	    getMessages();
	    
	    
	    library = ApplicationService.getLibrary();
        String message = library +"  Level: " + selected_level +"  Seat: " + selected_seat;
        
        TextView tv = (TextView) findViewById(R.id.sigin_lib_name);
        tv.setText(message);
        
  }  
    
    
    
    @Override
    public void onResume() {
    	super.onResume();
    	autoUpdate = new Timer();
    	autoUpdate.schedule(new TimerTask() {
      @Override
      public void run() {
       runOnUiThread(new Runnable() {
        public void run() {
        	getMessages();
        }
       });
      }
     }, 0, 5000); // updates each 5 seconds
    }
   
    @Override
    public void onPause() {
	     autoUpdate.cancel();
	     super.onPause();
    }
    
    public void onClickHandler(View view) {
    	String url = HOSTNAME + UPDATE_MESSAGE_BOARD_URL + "?sender=" + deviceID + "&library=" + library + "&level=" + selected_level + "&seat=" + selected_seat + "&message=" + message_et.getText().toString();
    	
    	// Send new message and update screen
    	new GetJSONArrayTask(){
    		@Override
    		protected void onPostExecute(JSONArray result){
				if(result == null){
					ApplicationService.inform(getString(R.string.nointernet));
					finish();
					return;
				}         		
				
				messages = result;
				message_et.setText("");				
				imm.hideSoftInputFromWindow(message_et.getWindowToken(), 0);
				
				msg_len = messages.length();
				
				msgTable.removeAllViews();
				// Parse JSON Object				
                try{
                	for(int i=0; i<messages.length(); i++) {
                		String tempString = "";
                		
                		JSONObject json_data = messages.getJSONObject(i);
                		
        		    	TableRow newRow = new TableRow(MessageBoardActivity.this);
        		    	TextView msg = new TextView(MessageBoardActivity.this);
        		    	
        		    	tempString = json_data.getString("name") + ": " +json_data.getString("time") + "\n" + json_data.getString("message");
        		    	;
        		    	msg.setText(tempString);
        		    
        		    	msg.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD), 0);
        				
        		    	// Current user
        		    	if(json_data.getString("name").equals(username))
        		    	{
        		    		newRow.setGravity(Gravity.RIGHT);
        		    		msg.setGravity(Gravity.RIGHT);
        		    		
        		    		msg.setTextColor(Color.YELLOW);
        		    		
        		    	}else {
        		    		msg.setTextColor(Color.GRAY);
        		    	}
        				
        				newRow.addView(msg);
        				newRow.setBackgroundColor(Color.TRANSPARENT);
        				msgTable.addView(newRow); 
        				msgTable.setBackgroundColor(Color.TRANSPARENT);
        				// Save the chat text to the global object for reference
        				String tempString2 = globalObject.getMsgBoardText();
        				globalObject.setMsgBoardText(tempString2 += tempString + "\n"	); 
        				
        			
        				
        				
        			
                	}                	                	
                }
                catch(JSONException e){
                	Log.e(TAG, "Error parsing data "+e.toString());
                }         		
         	}	
        }.execute(url.replaceAll(" ", "%20"));	
    	
    }
    
	public void onSaveHandler(View view) {
    	intent = new Intent(MessageBoardActivity.this, EmailActivity.class);
    	startActivity(intent);
    }

    private void getMessages(){
    	String url = HOSTNAME + UPDATE_RECEIVER_BOARD_URL + "?library=" + library + "&level=" + selected_level + "&seat=" + selected_seat;           
    	
    	// Get current messages
    	new GetJSONArrayTask(){
    		@Override
    		protected void onPostExecute(JSONArray result){
				if(result == null){
					ApplicationService.inform(getString(R.string.nointernet));
					finish();
					return;
				}         		
				
				messages = result;
				
				if(msg_len == messages.length())
					return;
				
				msgTable.removeAllViews();
				msg_len = messages.length();				
							
				// Parse JSON Object				
                try{
                	for(int i=0; i<messages.length(); i++) {
                		
                		JSONObject json_data = messages.getJSONObject(i);
                		
        		    	TableRow newRow = new TableRow(MessageBoardActivity.this);        		    	
        		    	TextView msg = new TextView(MessageBoardActivity.this);
        		    	
        		    	msg.setText(json_data.getString("name") + ": " + json_data.getString("time") + "\n" + json_data.getString("message"));        		    	
        		    	
        		    	// Current user
        		    	if(json_data.getString("name").equals(username))
        		    	{
        		    		newRow.setGravity(Gravity.RIGHT);
        		    		msg.setGravity(Gravity.RIGHT);
        		    		msg.setTextColor(Color.YELLOW);
        		    		
        		    	}else {
        		    		msg.setTextColor(Color.GRAY);
        		    	}
        		    	        		    	
        				newRow.addView(msg); 
        				newRow.setBackgroundColor(Color.TRANSPARENT);
        				
        				msgTable.addView(newRow);
        				msgTable.setBackgroundColor(Color.TRANSPARENT);
                	}                	                	
                }
                catch(JSONException e){
                	Log.e(TAG, "Error parsing data "+e.toString());
                }         		
         	}	
        }.execute(url.replaceAll(" ", "%20"));	
    }       

}


